<?php
namespace app\event;

use think\Db;

class ModelOptimisticEvent
{
    const LOCK_VERSION = 'lock_version';

    public function beforeUpdate($model)
    {
        /**
         * @var $model \think\Model
         */
        /** 取出字段名 */
        $fields = $model->getTableFields($model->getTable());
        /** 判断是否有lock_version 字段 */
        if (in_array(self::LOCK_VERSION, $fields)) {
            $lockVersion = Db::table($model->getTable())
                ->where($model->getPk(), $model[$model->getPk()])
                ->value(self::LOCK_VERSION);
            /** 判断版本号是否一致 */
            if ($model[self::LOCK_VERSION] == $lockVersion) {
                $model[self::LOCK_VERSION] = $model[self::LOCK_VERSION] + 1; //版本号加1
                return true;
            }
            return false;
        }
        return true;
    }
}
